#!/usr/bin/env python
#coding=utf-8

import sys
import os

def searchImg(dir, key, outdir):
    _list = []
    for _root, _dirs, _files in os.walk(dir):
        for _f in _files:
            _f = _f.lower()
            if _f.endswith('.img') and _key.lower() in _f:
                print ' found', os.path.join(_root, _f)
                _list.append([os.path.join(_root, _f), os.path.join(outdir, os.path.splitext(_f)[0] + '.tif')])
                
    return _list
    
if __name__ == '__main__':
    if len(sys.argv) != 4:
        print 'usage: img2tif.py inputdir keyword outpudir'
        sys.exit(0)
    
    _search = sys.argv[1]
    _key = sys.argv[2]
    _outdir = sys.argv[3]
    
    _dir = sys.path[0]
    _scriptPath = os.path.join(_dir, 'tmp\\' + _key + '.bat')
    
    _out = file(_scriptPath, 'w');
    _gdalData = os.path.join(_dir, 'gdal\\data')
    _gdalBin = os.path.join(_dir, 'gdal\\bin')
    _gdalCmd = os.path.join(_dir, 'gdal\\bin\\gdal_translate.exe')
    
    if _gdalBin not in sys.path:
        _out.write('set PATH=' + _gdalBin + ';%PATH%\n')
    
    _out.write('set GDAL_DATA=' + _gdalData + '\n')
    
    _list = searchImg(_search, _key, _outdir)
    for _f1, _f2 in _list:
        _out.write(_gdalCmd + ' "' + _f1 + '" "' + _f2 + '"\n')
    
    _out.close()
    
    print 'found', len(_list), 'images. '
    if raw_input('tranlate? (y/n):') == 'y':
        os.system(_scriptPath)

